package controllers

import (
	"strconv"

	"myblog/utils"

	beego "github.com/beego/beego/v2/server/web"
)

type MainController struct {
	beego.Controller
}

func (this *MainController) Get() {
	id := this.Ctx.Input.Param(":id")
	idint, _ := strconv.Atoi(id)

	//获取目录文件名
	postdir, _ := beego.AppConfig.String("postdir")
	postdir = utils.GetCurrentPath() + postdir
	files, _ := utils.ListDir(postdir)

	//每页条数
	pre, _ := beego.AppConfig.String("pages")
	preint, _ := strconv.Atoi(pre)
	//获取数据总数
	pagenumber := int64(len(files))

	//首页文章字数
	contennumbers, _ := beego.AppConfig.String("contennumbers")
	contennumbersint, _ := strconv.Atoi(contennumbers)

	//将当前页数id,数据总数传入分页功能函数
	pager := utils.Pages(idint, preint, pagenumber)

	var filestitle []utils.Filetile
	if len(files) > preint {
		filestitle = utils.ReadFilesTile(files[(idint-1)*preint : idint*preint])
	} else {
		filestitle = utils.ReadFilesTile(files)
	}

	for v, _ := range filestitle {
		if len(filestitle[v].Content) >= contennumbersint {
			filestitle[v].Content = filestitle[v].Content[1:contennumbersint]
		}
	}

	this.Data["Pages"] = pager["pages"]
	this.Data["Currpage"] = pager["currpage"]
	this.Data["Previous"] = pager["firstpage"]
	this.Data["Next"] = pager["lastpage"]

	this.Data["Filestitle"] = filestitle
	this.TplName = "model/body.tpl"
	this.LayoutSections = make(map[string]string)
	this.LayoutSections["IndexHead"] = "model/head.tpl"
	this.LayoutSections["IndexNavbar"] = "model/navbar.tpl"
	this.LayoutSections["IndexNav"] = "model/nav.tpl"
	this.LayoutSections["IndexFoot"] = "model/foot.tpl"
	this.Layout = "index.tpl"

}
